<?php

require_once 'BluesCoders/Request/Http/Session/IStorage.php';
require_once 'BluesCoders/Event/Listener.php';
/**
 * Description of PhpStorage
 *
 * @author miho
 */
class BluesCoders_Request_Http_Session_PhpStorage implements
                            BluesCoders_Request_Http_Session_IStorage

{

    protected $_data;

    protected $_opened = false;

    public function  __construct() {
        BluesCoders_Event_Dispatcher::getIsntance()->addEventListener(
            BluesCoders_Application_Event::SHUT_DOWN,
            new BluesCoders_Event_Listener($this, 'applicationShutDownHandler')
        );
    }

    public function applicationShutDownHandler($event){
        $this->commit();
        //$this->close();
    }

    public function open() {
        if(session_start() === false) {
            throw new Exception("Fail to start PHP session");
        }

        $this->_data = $_SESSION;
        //unset($_SESSION);
        $this->_opened = true;
    }

    public function getObject($name) {
        return isset($this->_data[$name]) ? $this->_data[$name] : null;
    }

    public function setObject($name, $value) {
        $this->_data[$name] = $value;
        return $this;
    }

    public function commit() {
        $_SESSION = $this->_data;
    }

    public function close() {
        if(! $this->_opened) {
            throw new Exception("Session does not opened or already closed");
        }
        session_destroy();
    }
}
?>
